package com.engr.springbooteasypoi.thread;

import java.util.concurrent.Semaphore;

/**
 * @author : liuYanXin
 * @Description : 信号量实例
 * @Date : 2020-03-30
 */
public class SemaphoreCls {

    public static void main(String[] args) {
        Thread[] threads = new Thread[10];

        PrintQueue printQueue = new PrintQueue();

        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(new Job(printQueue), "Thread_" + i);
        }

        for (int i = 0; i < 10; i++) {
            threads[i].start();
        }
    }
}

class PrintQueue {

    private final Semaphore semaphore;

    PrintQueue() {
        this.semaphore = new Semaphore(1);
    }

    public void printJob(Object document) {

        try {
            semaphore.acquire();
            long duration = (long) (Math.random() * 10);
            System.out.println(Thread.currentThread().getName() +
                    "PrintQueue : Printing a job during " + duration);
            Thread.sleep(duration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }
}

class Job implements Runnable {

    private PrintQueue printQueue;

    public Job(PrintQueue printQueue) {
        this.printQueue = printQueue;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " Going to print a job");
        printQueue.printJob(new Object());
        System.out.println(Thread.currentThread().getName() + " the document has bean printed");
    }
}
